﻿#include"List.h"
//添加节点
LTNode* buyNode(LTDatatype x) {
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	node->data = x;
	node->next = node->prev = node;
	return node;
}
//初始化
LTNode* LTInit() {
	LTNode* phead = buyNode(-1);
	return phead;
}
//打印链表
void LTPrint(LTNode* phead) {
	LTNode* pcur = phead->next;
	while (pcur != phead) {
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}
//判断链表是否为空
bool LTEmpty(LTNode* phead) {
	assert(phead);
	return phead->next == phead;
	//如果这个表达式为真说明链表为空 
}
//尾插
void LTPushBack(LTNode* phead, LTDatatype x) {
	LTNode* newnode = buyNode(x);
	newnode->prev = phead->prev;
	newnode->next = phead;
	phead->prev->next = newnode;
	phead->prev = newnode;
}
//头插
void LTPushFront(LTNode* phead, LTDatatype x) {
	assert(phead);
	LTNode* newnode = buyNode(x);
	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;
}
//尾删
void LTPopBack(LTNode* phead) {
	assert(!LTEmpty(phead));
	LTNode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
	del = NULL;
}
//头删
void LTPopFront(LTNode* phead) {
	assert(!LTEmpty(phead));
	LTNode* del = phead->next;
	del->next->prev = phead;
	phead->next = del->next;
	free(del);
	del = NULL;
}
//查找某个数据在链表中的位置
LTNode* LTFind(LTNode* phead, LTDatatype x) {
	LTNode* pcur = phead->next;
	while (pcur != phead) {
		if (pcur->data == x) {
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;//没找到 返回空
}
//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDatatype x) {
	assert(pos);
	LTNode* newnode = buyNode(x);
	newnode->next = pos->next;
	newnode->prev = pos;
	pos->next->prev = newnode;
	pos->next = newnode;
}
//删除pos位置的数据
void LTErase(LTNode* pos) {
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
	pos = NULL;
}
//销毁链表
void LTDesTroy(LTNode* phead) {
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}